import base64
import datetime
import json
from io import BytesIO

from django.shortcuts import render
from django.http import JsonResponse
import time

from rest_framework.views import APIView

from apps.app_tempapi.utils.code import check_code, image_to_base64
from apps.app_tempapi.utils.encrypt import generate_has, md5

data = {
    "data": [
        {
            "id": 45,
            "name": "谢新雪",
            "area": "#19",
            "avatar": "http://127.0.0.1:8000/media/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240427181120_0.jpg"
        }
    ],
    "today_count": 10,
    "total_count": 3
}


def acquisition(request):
    global data
    data = data
    return JsonResponse(data)


def list_delete(request, nid):
    global data
    nid = int(nid)
    for index, person in enumerate(data['data']):
        if person["id"] == nid:
            data['data'].pop(index)
            data['today_count'] -= 1
            data['total_count'] -= 1
            break
    else:
        print(f"没有找到id为{nid}的字典。")
        return JsonResponse({})
    return JsonResponse(data)


BILL_DATA = [
    {"id": 38, "name": '球鞋', "price": 299, "creator": "小黑"},
    {"id": 37, "name": '防晒霜', "price": 99, "creator": "小黑"},
    {"id": 36, "name": '手表', "price": 588, "creator": "小黑"},
    {"id": 35, "name": '棉大衣', "price": 199, "creator": "小黑"},
    {"id": 34, "name": '鸭舌帽', "price": 99, "creator": "小黑"},
]


class Bill(APIView):

    def get(self, request):
        global BILL_DATA
        data = {
            "data": BILL_DATA
        }
        return JsonResponse(data)

    def post(self, request):
        data = request.data
        max_id_item = max(BILL_DATA, key=lambda x: x['id'])
        data['id'] = max_id_item['id'] + 1
        BILL_DATA.insert(0, data)

        data = {
            "data": BILL_DATA
        }
        return JsonResponse(data)


class BillDetail(APIView):

    def delete(self, request, pk):
        global BILL_DATA
        BILL_DATA = list(filter(lambda x: x['id'] != pk, BILL_DATA))
        return JsonResponse({})


code = ''
b64_key = ''


class captchaImage(APIView):

    def get(self, requests):
        global code, b64_key
        img, code = check_code()
        img_base64 = image_to_base64(img)
        b64_key = base64.b64encode(generate_has(bytes(code, 'utf8'))).decode('utf-8')
        data = {
            "status": 200,
            "message": "success",
            "data": {
                "base64": img_base64,
                "key": b64_key,
                "md5": md5(code)
            }
        }
        return JsonResponse(data)


class sendSmsCaptcha(APIView):

    def post(self, request):
        data = request.data['form']
        captcha_code = data['captchaCode']
        captcha_key = data['captchaKey']
        if captcha_code.upper() == code.upper() and captcha_key == b64_key:
            data = {"status": 200, "message": "^_^小智提示: 测试环境验证码为: 246810", "data": []}
            return JsonResponse(data)
        data = {
            "message": "很抱歉，图片验证码不正确",
            "status": 500,
            "data": []
        }
        return JsonResponse(data)

def cat_path(request):
    print(json.loads(request.body))
    time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    with open('apps/app_tempapi/log/history.log', mode='a', encoding='utf8') as f:
        f.write('info ' + str(datetime.datetime.now()) + ' ' + str(json.loads(request.body)) + '\n')
    return JsonResponse({}, status=200)